define(['angularAMD'], function (angularAMD) {
    angularAMD.service('B0208Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog','$mddProvider',
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $mddProvider){
            ///options : {
            ///    machine_no,
            ///    plotItem,
            ///    feedback
            ///}
            this.init = function(options){
                $MMWService.PNIGList = {};
                var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');
                var stopInfo={
                    op_no:options.plotItem.op_no,
                    plot_no:options.plotItem.plot_no,
                    qty: options.plotItem.qty||0,
                    plot_stamp: options.plotItem.plot_stamp,
                    status: options.plotItem.status,
                    working_type:1,
                    rework_flag:0,
                    wait_reason_detail:[]
                };

                // 20191128 modify by WeiTing for M#64745 - 判斷派工數量(dispatch_qty)和進站數量(qty)，哪個少就帶少的那個。
                // 20191231 modify by Dustdusk for M#65655: 調整邏輯
                options.plotItem.dispatch_qty = options.plotItem.dispatch_qty||0;
                if(stopInfo.qty > options.plotItem.dispatch_qty && options.plotItem.dispatch_qty != 0){
                    //派工數量少並且不為0則使用派工數量
                    stopInfo.qty = options.plotItem.dispatch_qty;
                }

                function SMES_PlotWaitSetProcess(dialog) {
                    var content={
                        op_no: stopInfo.op_no,
                        equipment_no: options.machine_no,
                        plot_no: stopInfo.plot_no,
                        working_type: stopInfo.working_type,
                        qty: stopInfo.qty,
                        plot_stamp:stopInfo.plot_stamp,
                        status : stopInfo.status,
                        rework_flag:stopInfo.rework_flag,
                        lot_state_curqty:stopInfo.lot_state_curqty,
                        equipment_input_qty:stopInfo.equipment_input_qty,
                        wait_reason_detail:[]
                    };
                    stopInfo.wait_reason_detail.forEach(function (item) {
                        if(item.reason_no){
                            content.wait_reason_detail.push({reason_no:item.reason_no});
                        }
                    });
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_WIP.plot_wait_set_process',
                        content : content,
                        success : function(data){
                            $rootScope.showToast($filter('translate')('B0208.msg.success'));
                            dialog.hide();
                            // 20240325 modify by wenwei for M#160267: [Oracle][H5][设备稼动]生产线工作平台-暂停后设备状态未变
                            if(options.feedback) {
                                var work_time = $filter('date')(nowdatetime.split(' ')[0], 'yyyy/MM/dd') + " " + nowdatetime.split(' ')[1];
                                options.feedback({
                                    machine_no: content.equipment_no,
                                    report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                    machine_status: '1',
                                    remark: '',
                                    handle_user_no: config.cache.account,
                                    plan_start_time: work_time,
                                    actual_end_time: work_time ,
                                    remarks: undefined
                                });
                            }
                        }
                    });
                }

                function SMES_PlotWaitInfoGet(callback){
                    var content={
                        op_no: options.plotItem.op_no,
                        plot_no: options.plotItem.plot_no,
                        trigger_point: '0', //0 (暫停), 1 (解除暫停)
                        machine_no: options.machine_no,
                        status: stopInfo.status
                    };
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_WIP.plot_wait_info_get',
                        content : content,
                        success : function(data){
                            if(callback)
                                callback(data);
                        }
                    });
                }

                function itemCheck(index,item) {
                    if(!item.checked || item.checked=='Y'){
                        item.checked = 'N';
                    } else {
                        item.checked = 'Y';
                        stopInfo.wait_reason_detail[index].reason = item.reason;
                    }
                }

                //開啟暫停視窗
                function openDialog(response) {
                    $mddProvider.UseForm('B0208Service', () => {
                        $mdDialog.dialog('module/moduleB/program/B02/B0208/B0208.html',
                            function (dialog) {
                                return {
                                    css_url: 'JSplugins/angular-material-lite/template/dynamicService.tmp.css',
                                    stopInfo: stopInfo,
                                    itemCheck: itemCheck,
                                    _event: {
                                        'wait_reason_detail.reason_name': {
                                            click: () => {
                                                dialog.loadReworkReasonList();
                                            }
                                        }
                                    },
                                    _fn: {
                                        'addRow': {
                                            click: () => {
                                                dialog.loadReworkReasonList();
                                            }
                                        },
                                        'Confirm': {
                                            click: () => {
                                                if (stopInfo.wait_reason_detail.length != 0) {
                                                    var isOK = true;
                                                    stopInfo.wait_reason_detail.forEach(function (detail) {
                                                        if (!detail.page_no || detail.page_no == '') {
                                                            isOK = false;
                                                        }
                                                    });
                                                    if (isOK) {
                                                        SMES_PlotWaitSetProcess(dialog);
                                                    } else {
                                                        $rootScope.showAlert($filter('translate')('B0208.showAlert.column2'));
                                                    }
                                                } else {
                                                    $rootScope.showAlert($filter('translate')('B0208.showAlert.column2'));
                                                }
                                            }
                                        }
                                    },
                                    loadReworkReasonList: function (item) {
                                        $rootScope.showQueryList({
                                            key: 'page_no',
                                            title: $filter('translate')('common.queryList.stopReason_select'),
                                            header: [
                                                { label: $filter('translate')('common.queryList.reason_c'), code: 'page_no' },
                                                { label: $filter('translate')('common.queryList.reason_n'), code: 'page_name' }
                                            ],
                                            query: function (conditions, feedback) {
                                                feedback(response);
                                            },
                                            confirm: function (selectItem, radioDialog) {
                                                if (item != undefined) {
                                                    item.reason_no = selectItem.page_no;
                                                    item.page_no = selectItem.page_no;
                                                    item.page_name = selectItem.page_name;
                                                    item.reason_name = selectItem.page_no + ' ' + selectItem.page_name;
                                                } else {
                                                    stopInfo.wait_reason_detail.push({
                                                        reason_no: selectItem.page_no,
                                                        page_no: selectItem.page_no,
                                                        page_name: selectItem.page_name,
                                                        reason_name: selectItem.page_no + ' ' + selectItem.page_name
                                                    });
                                                }
                                                radioDialog.hide();
                                            }
                                        });
                                    },
                                    addRow: function () {
                                        //stopInfo.wait_reason_detail.push({reason:''});
                                        dialog.loadReworkReasonList();
                                    },
                                    removeRow: function (index) {
                                        stopInfo.wait_reason_detail.splice(index, 1);
                                    }
                                }
                            }
                        );
                    })
                    
                }

                (function(){
                    //取得暫停原因
                    //20180525 modify by 李栋 for mantis#0047129
                    $MMWService.pageNumberInfoGet({
                        //20220601 modify by wangzy for M#0113181: [sMES] 例外處理報廢入庫，報廢原因有簽核但介面點新增出現：查無資料! [旭東]
                        form_name: 'PageNo_53',
                        query_condition_info: [
                            { column_name: 'ReasonType', query_mode: 0, value: 8, merge_condition_model: 'AND' }
                        ]
                    }, function(itemList){
                        SMES_PlotWaitInfoGet(function(data){
                            if(data.lot_state_curqty)
                                stopInfo.lot_state_curqty = data.lot_state_curqty;
                            else
                                stopInfo.lot_state_curqty = 0;
                            if(data.equipment_input_qty)
                                stopInfo.equipment_input_qty = data.equipment_input_qty;
                            else
                                stopInfo.equipment_input_qty = 0; 
                            openDialog(itemList.slice());
                        });
                    });
                })();
            };
        }]);
});
